/*
 * Copyright 2015 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package course.homework;

import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;

import freemarker.template.Configuration;
import freemarker.template.Template;

import org.bson.Document;
import org.bson.types.ObjectId;

import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import static java.util.Arrays.asList;

public class MongoFinal {
    public static void main(String[] args)  {
        MongoFinal mongo = new MongoFinal();
        
        mongo.answer7();
    }
    private void answer7() {
    	MongoClient c =  new MongoClient("192.168.1.3:8080");
        MongoDatabase db = c.getDatabase("photos");
        MongoCollection<Document> albums = db.getCollection("albums");
        MongoCollection<Document> images = db.getCollection("images");

       FindIterable<Document> filter = images.find().filter(new Document());
       MongoCursor<Document> iterator = filter.iterator();
       Set<Integer> imgIds = new HashSet<Integer>();
       while(iterator.hasNext())
       {
    	   imgIds.add((Integer) iterator.next().get("_id"));
    	   //System.out.println(iterator.next().get("_id"));
       }
       //System.out.println(imgIds.size());
       
       filter = albums.find();
       iterator = filter.iterator();
       while(iterator.hasNext())
       {
    	   Document next = iterator.next();
    	   List<Integer> object = (List<Integer>) next.get("images");
    	   for(Integer img : object)
    	   {
    		   imgIds.remove(img);
    	   }
       }
       System.out.println(imgIds.size());
       Iterator<Integer> iter = imgIds.iterator();
       while(iter.hasNext())
       {
    	   images.deleteOne(new Document("_id", iter.next()));
       }
	}
    
    private void answer8() {
    	MongoClient c =  new MongoClient("192.168.1.3");
        MongoDatabase db = c.getDatabase("test");
        MongoCollection<Document> animals = db.getCollection("animals");

       Document animal = new Document("animal", "monkey");

        animals.insertOne(animal);
        animal.remove("animal");
        animal.append("animal", "cat");
        animals.insertOne(animal);
        animal.remove("animal");
        animal.append("animal", "lion");
        animals.insertOne(animal);
	}
	public void answer2()
    {
    	MongoClient client = new MongoClient("192.168.1.3");
        MongoDatabase database = client.getDatabase("enron");
        final MongoCollection<Document> coll = database.getCollection("messages");
        
        //long count = coll.count(new Document("headers.From", "andrew.fastow@enron.com"));
        Document query = new Document();
        
		FindIterable<Document> results = coll.find(query);
		results.projection(new Document("_id", 0).append("body", 0));
        MongoCursor<Document> iterator = results.iterator();
        Set<Object> set = new HashSet<Object>();
        //LinkedList<Object> set = new LinkedList();
        Map<String,Integer> mapDirectional = new HashMap<String, Integer>();
        Map<String,Integer> map = new HashMap<String, Integer>();
        while(iterator.hasNext())
        {
        	Document inner = (Document) iterator.next().get("headers");
        	ArrayList<String> addr = (ArrayList<String>) inner.get("To");
        	if(addr==null)
        		continue;
        	for(String add : addr)
        	{
        		if(add.equals("recipients@enron.com"))
        			continue;
        		String key = (String) inner.get("From")+"|"+add;
        		Integer value = mapDirectional.get(key);
				if(value==null)
					value = 0;
        		mapDirectional.put(key, ++value);
        		
        		
        		List<String> asList = new ArrayList<String>(Arrays.asList((String) inner.get("From"),add));
        		Collections.sort(asList);
				key = asList.get(0)+"|"+asList.get(1);
				value = map.get(key);
				if(value==null)
					value = 0;
        		map.put(key, ++value);
        	}
        }
        Iterator<Entry<String, Integer>> iter = mapDirectional.entrySet().iterator();
       int curCount = 0;
        String curKey = "";
        while(iter.hasNext())
        {
        	Entry<String, Integer> next = iter.next();
        	if(curCount<next.getValue())
        	{
        		curCount = next.getValue();
        		curKey = next.getKey();
        	}
        }
        System.out.println(curKey + " " + curCount);
        curCount = 0;
        curKey = "";
        iter = map.entrySet().iterator();
        while(iter.hasNext())
        {
        	Entry<String, Integer> next = iter.next();
        	if(curCount<next.getValue())
        	{
        		curCount = next.getValue();
        		curKey = next.getKey();
        	}
        }
        System.out.println(curKey + " " + curCount);
        
        while(iter.hasNext())
        {
        	Entry<String, Integer> next = iter.next();
        	System.out.println(next.getKey() +" " + next.getValue());
        }
    }
    
    public void answer1()
    {
    	MongoClient client = new MongoClient("192.168.1.3");
        MongoDatabase database = client.getDatabase("enron");
        final MongoCollection<Document> coll = database.getCollection("messages");
        
        //long count = coll.count(new Document("headers.From", "andrew.fastow@enron.com"));
        Document query = new Document("headers.From","andrew.fastow@enron.com");
        
		FindIterable<Document> results = coll.find(query);
		//results.projection(new Document("_id", 0).append("headers.To", 1));
        MongoCursor<Document> iterator = results.iterator();
        Set<Object> set = new HashSet<Object>();
        //LinkedList<Object> set = new LinkedList();
        while(iterator.hasNext())
        {
        	Document inner = (Document) iterator.next().get("headers");
        	//ArrayList<String> addr = (ArrayList<String>) inner.get("Bcc");
			set.add(inner.get("Cc"));
        }
        Iterator<Object> iter = set.iterator();
        while(iter.hasNext())
        {
        	System.out.println(iter.next());
        }
    }
}
